package com.adxon.cookie;

import com.adxon.MsgException;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Kooky{
	private static String[] cls=
		{"com.adxon.cookie.Station","com.adxon.cookie.Badge"};
	@SuppressWarnings("rawtypes")
	private static Map<String,Class>	map=init();

	protected final static void getAll(HttpServletRequest req){
		if(req.getAttribute("kky")==null)try{
			Cookie[]s=req.getCookies();
			if(s!=null)for(Cookie c:s){
				@SuppressWarnings("rawtypes")
				Class a=map.get(c.getName());
				if(a!=null){
					Kooky x=(Kooky)a.newInstance();
					x.set(req,c);
				}
			}
			req.setAttribute("kky",true);
		}catch(InstantiationException e){
			e.printStackTrace();
		}catch(IllegalAccessException e){
			e.printStackTrace();
		}catch(MsgException e){
			//e.printStackTrace();
		}
	}
	@SuppressWarnings("rawtypes")
	private static Map<String,Class> init(){
		Map<String,Class> r=new TreeMap<String,Class>();
		try{
			for(String s:cls){
				Class c=Class.forName(s);
				Kooky k=(Kooky)c.newInstance();
				System.out.println(s+": "+k.idx);
				r.put(k.idx,c);
			}
		}catch(IllegalAccessException e){
			e.printStackTrace();
		}catch(InstantiationException e){
			e.printStackTrace();
		}catch(ClassNotFoundException e){
			e.printStackTrace();
		}
		return r;
	}
	protected static String toGMTString(Date date) {  
		SimpleDateFormat f=new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z",Locale.UK);  
		f.setTimeZone(new java.util.SimpleTimeZone(0,"GMT"));  
		return f.format(date);  
	}

	protected String	atr;	// attribute for request
	protected Cookie	cki;
	protected boolean	htp;	// http only
	protected String	idx;

	public void addTo(HttpServletResponse resp){
		if(cki!=null)
			resp.addCookie(cki);
	}
	public void set(HttpServletRequest req,Cookie src)throws MsgException{
		cki=src;
		req.setAttribute(atr,this);
	}
}